package com.stenio.fancat.service.shop;

import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.shop.FcShop;
import com.stenio.fancat.domain.shop.FcShopImage;
import com.stenio.fancat.mapper.shop.FcShopImageMapper;
import com.stenio.fancat.service.OssService;
import com.stenio.fancat.service.enums.ImageType;
import org.omg.CORBA.INTERNAL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class ShopImageService extends ServiceImpl<FcShopImageMapper, FcShopImage> {

	@Autowired
	private FcShopImageMapper fcShopImageMapper;

	@Autowired
	private OssService ossService;

	@Value("${oss.piggybank.endpoint}")
	private String piggybankEndPoint;

	private static final Logger logger = LoggerFactory.getLogger(ShopImageService.class);

	/**
	 * 保存图片
	 * @param file
	 * @param type
	 * @return
	 */
	public FcShopImage saveImage(MultipartFile file, Integer type){
		FcShopImage image = new FcShopImage();
		Date date = new Date();
		image.setCreateTime(date);
		image.setUpdateTime(date);
		try {
			image.setType(ImageType.getEnumByType(type).getType());
			String fileName = getImageName(file.getOriginalFilename());
			image.setUrl(piggybankEndPoint+fileName);
			ossService.putObject(fileName,file.getBytes());
			image.setName(file.getOriginalFilename());
			fcShopImageMapper.insert(image);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	/**
	 * 生成图片新的名字
	 * @param sourceName
	 * @return
	 */
	private String getImageName(String sourceName){
		StringBuffer sb = new StringBuffer();
		sb.append(UUID.randomUUID().toString());
		sb.append(sourceName.substring(sourceName.lastIndexOf(".")));
		return sb.toString();
	}

	/**
	 * 将图片和业务id进行关联
	 * @param bizId
	 * @param imageId
	 */
	public void updateBiz(Integer bizId, Integer imageId){
		FcShopImage image = new FcShopImage();
		image.setId(imageId);
		image.setBusinessId(bizId);
		fcShopImageMapper.updateBiz(image);
	}

	/**
	 * 根据业务id和图片的类型查询
	 * @param image
	 * @return
	 */
	public List<FcShopImage> selectByType(FcShopImage image){
		return fcShopImageMapper.selectByType(image);
	}

	public void deleteById(Integer id){
		fcShopImageMapper.deleteById(id);
	}



}
